package com.example.service.impl;

import com.example.dao.OrderDao;
import com.example.dao.OrderDetailDao;
import com.example.entity.Order;
import com.example.entity.OrderDetail;
import com.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;

/**
 * 订单服务实现类
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    private final OrderDao orderDao;
    private final OrderDetailDao orderDetailDao;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    public OrderServiceImpl(OrderDao orderDao, OrderDetailDao orderDetailDao) {
        this.orderDao = orderDao;
        this.orderDetailDao = orderDetailDao;
    }

    @Override
    public List<Order> getOrdersByUserId(Integer userId) throws IllegalArgumentException {
        // 参数校验
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不能为空且必须大于0");
        }

        // 查询订单
        List<Order> orders = orderDao.findByUserId(userId);

        // 记录日志
        if (orders.isEmpty()) {
            System.out.println("警告: 用户 " + userId + " 没有查询到任何订单");
        } else {
            System.out.println("成功查询到用户 " + userId + " 的 " + orders.size() + " 笔订单");
        }

        return orders;
    }

    @Override
    public boolean cancelOrder(Integer orderId) {
        // 参数校验
        if (orderId == null || orderId <= 0) {
            System.out.println("错误: 无效的订单ID");
            return false;
        }

        // 检查订单是否存在
        Order order = orderDao.findById(orderId);
        if (order == null) {
            System.out.println("错误: 订单 " + orderId + " 不存在");
            return false;
        }

        // 检查订单状态
        if ("cancelled".equalsIgnoreCase(order.getOrderstatus())) {
            System.out.println("警告: 订单 " + orderId + " 已经是取消状态");
            return false;
        }

        // 执行取消操作
        boolean success = orderDao.updateStatus(orderId, "cancelled") > 0;
        if (success) {
            System.out.println("成功取消订单: " + orderId);
        } else {
            System.out.println("取消订单失败: " + orderId);
        }
        return success;
    }

    @Override
    public boolean createOrder(Order order) throws IllegalArgumentException {
        // 参数校验
        if (order == null) {
            throw new IllegalArgumentException("订单对象不能为空");
        }
        if (order.getUserid() == null || order.getUserid() <= 0) {
            throw new IllegalArgumentException("无效的用户ID");
        }
        if (order.getRecipeid() == null) {
            throw new IllegalArgumentException("必须指定菜品ID");
        }

        // 设置订单默认值
        order.setOrdertime(dateFormat.format(new Date()));
        order.setOrderstatus("pending");

        // 创建订单
        boolean success = orderDao.insert(order) > 0;
        if (success) {
            System.out.println("成功创建订单: " + order.getUserid());
        } else {
            System.out.println("创建订单失败");
        }
        return success;
    }

    @Override
    public boolean updateOrderStatus(Integer orderId, String status) {
        // 参数校验
        if (orderId == null || orderId <= 0) {
            System.out.println("错误: 无效的订单ID");
            return false;
        }
        if (status == null || status.trim().isEmpty()) {
            System.out.println("错误: 状态不能为空");
            return false;
        }

        // 检查订单是否存在
        if (orderDao.findById(orderId) == null) {
            System.out.println("错误: 订单 " + orderId + " 不存在");
            return false;
        }

        // 更新状态
        boolean success = orderDao.updateStatus(orderId, status) > 0;
        if (success) {
            System.out.println("成功更新订单 " + orderId + " 状态为: " + status);
        } else {
            System.out.println("更新订单状态失败: " + orderId);
        }
        return success;
    }

    @Override
    public Order createOrderFromCart(String shopcartIds, Integer userid) {
        // 1. 参数校验
        if (shopcartIds == null || shopcartIds.isEmpty()) {
            throw new IllegalArgumentException("购物车ID不能为空");
        }
        if (userid == null || userid <= 0) {
            throw new IllegalArgumentException("无效的用户ID");
        }

        // 2. 创建主订单
        Order order = new Order();
        order.setUserid(userid);
        order.setOrdertime(dateFormat.format(new Date()));
        order.setOrderstatus("pending");

        // 3. 保存订单并获取生成的ID
        if (orderDao.insert(order) <= 0) {
            throw new RuntimeException("订单创建失败");
        }

        // 4. 检查是否成功生成订单ID
        if (order.getOrderid() == null) {
            throw new RuntimeException("订单ID生成失败");
        }

        System.out.println("成功创建订单，订单ID: " + order.getOrderid());

        // 5. 处理购物车项
        String[] cartIds = shopcartIds.split(",");
        for (String cartId : cartIds) {
            try {
                int id = Integer.parseInt(cartId.trim());
                // 创建订单明细
                OrderDetail detail = new OrderDetail();
                detail.setOrderid(order.getOrderid());
                // 这里需要设置其他明细字段，如recipeid、num等
                // detail.setRecipeid(...);
                // detail.setNum(...);
                orderDetailDao.insert(detail);
            } catch (NumberFormatException e) {
                System.err.println("无效的购物车ID: " + cartId);
            }
        }

        return order;
    }

    @Override
    public boolean isOrderBelongToUser(Integer orderId, Integer userid) {
        return false;
    }

    @Override
    public Order getOrderById(Integer orderId) {
        // 1. 参数校验
        if (orderId == null || orderId <= 0) {
            throw new IllegalArgumentException("订单ID不能为空且必须大于0");
        }

        // 2. 查询订单主表
        Order order = orderDao.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 3. 查询订单明细
        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
        if (details == null) {
            details = new ArrayList<>(); // 防止NPE
        }

        // 4. 计算实时总价
        double total = details.stream()
                .mapToDouble(d -> d.getSubtotal() != null ? d.getSubtotal() : 0.0)
                .sum();
        order.setPrice(total);
        order.setOrderDetails(details);

        return order;
    }
}